<?php
defined('IN_IXDCW') or exit('Access Denied');

/**
 * 求购的类库文件
 */
class BuyModule extends BasicModule {

	/** @var 模块id */
	private $_moduleid;

	/** @var 条目ID */
	private $_itemid;

	/** @var string 表格 */
	private $_table;

	/** @var string 表格数据 */
	private $_tableData;

	/** @var 是否内容分表 */
	private $_split;

	/** @var array 可用字段 */
	private $_fields;

	/**
	 * @param $moduleid 模块id
	 *                  构造函数
	 */
	function __construct($moduleid) {
		parent::__construct();
		global $table, $table_data, $MOD;
		$this->_moduleid  = $moduleid;
		$this->_table     = $table;
		$this->_tableData = $table_data;
		$this->_split     = $MOD['split'];
		$this->_fields    = array('catid', 'areaid', 'arbid', 'arcid', 'amid', 'typeid', 'level', 'title', 'style', 'fee', 'introduce', 'amount', 'price', 'standard', 'pack', 'days', 'thumb', 'thumb1', 'thumb2', 'tag', 'status', 'hits', 'username', 'totime', 'editor', 'addtime',
			'adddate', 'edittime', 'editdate', 'ip', 'template', 'linkurl', 'note', 'company', 'truename', 'telephone', 'mobile', 'address', 'email', 'msn', 'qq', 'ali', 'skype');
	}

	public function setItemid($itemid) {
		$this->_itemid = $itemid;
	}

	public function getItemid() {
		return $this->_itemid;
	}

	public function getFields() {
		return $this->_fields;
	}

	/**
	 * @param $post
	 * @return bool 检测是否通过测试
	 */
	function pass($post) {
		global $DT_TIME;
		// post 注入
		if (!is_array($post)) return false;
		// 类别必须
		if (!$post['catid']) return $this->err(lang('message->pass_cate'));
		// title 长度太短
		if (strlen($post['title']) < 3) return $this->err(lang('message->pass_title'));

		// 下架时间
		if ($post['totime']) {
			if (!is_date($post['totime'])) return $this->err(lang('message->pass_date'));
			// 是否超出范围
			if (strtotime($post['totime'] . ' 23:59:59') < $DT_TIME) return $this->err(lang('message->pass_todate'));
		}
		return true;
	}

	/**
	 * @param $post
	 * @return array|mixed
	 * 设置 post 变量
	 */
	function set($post) {
		global $MOD, $DT_TIME, $DT_IP, $TYPE, $_username, $_userid, $r;
		// 编辑者
		$post['editor'] = $_username;
		// 添加时间
		$post['addtime'] = (isset($post['addtime']) && $post['addtime']) ? strtotime($post['addtime']) : $DT_TIME;
		// 添加日期
		$post['adddate'] = timetodate($post['addtime'], 3);
		// 编辑时间
		$post['edittime'] = $DT_TIME;
		// 编辑日期
		$post['editdate'] = timetodate($post['edittime'], 3);
		// 到期时间
		$post['totime'] = $post['totime'] ? strtotime($post['totime'] . ' 23:59:59') : 0;
		// 费率
		$post['fee'] = dround($post['fee']);
		// 标题
		$post['title'] = trim($post['title']);
		// 取消内容转义
		$post['content'] = stripslashes($post['content']);
		// 清除链接,模块设置
		if ($MOD['clear_link']) $post['content'] = Post::clearLink($post['content']);
		// 保存远程图片
		if ($MOD['save_remotepic']) $post['content'] = Post::saveRemote($post['content']);
		// 截取字串的简介的长度
		if ($MOD['introduce_length']) $post['introduce'] = addslashes(Post::intro($post['content'], $MOD['introduce_length']));

		if ($post['arbid']) {
			foreach ($post['arbid'] as $v) {
				if (!preg_match("/^\d*$/", $v)) {
					$post['arbid'] = '';
				}
			}
			sort($post['arbid']);
			$post['arbid'] = implode(',', $post['arbid']);
		} else {
			$post['arbid'] = '';
			$post['arcid'] = '';
			$post['amid']  = '';
		}
		if ($post['arcid'] && $post['arbid']) {
			foreach ($post['arcid'] as $v) {
				if (!preg_match("/^\d*$/", $v)) {
					$post['arcid'] = '';
				}
			}
			sort($post['arcid']);
			$post['arcid'] = implode(',', $post['arcid']);
		} else {
			$post['arcid'] = '';
			$post['amid']  = '';
		}
		if ($post['arcid'] && $post['arbid'] && $post['amid']) {
			foreach ($post['amid'] as $v) {
				if (!preg_match("/^\d*$/", $v)) {
					$post['amid'] = '';
				}
			}
			sort($post['amid']);
			$post['amid'] = implode(',', $post['amid']);
		} else {
			$post['amid'] = '';
		}

		if ($this->_itemid) {
			// 处理新传入的img
			$r              = $this->getOne();
			$post['editor'] = $_username;
		} else {
			$post['ip'] = $DT_IP;

		}
		if (!defined('DT_ADMIN')) {
			$content = $post['content'];
			unset($post['content']);
			$post            = Str::htmlSpecialChars($post);
			$post['content'] = Str::safe($content);
		}
		$post['content'] = addslashes($post['content']);
		return $post;
	}

	/**
	 * @return mixed 获取一条数据
	 */
	function getOne() {
		$content_table = content_table($this->_moduleid, $this->_itemid, $this->_split, $this->_tableData);
		return $this->_db->getOne("SELECT * FROM {$this->_table} a,{$content_table} c WHERE a.itemid=c.itemid and a.itemid=$this->_itemid");
	}

	/**
	 * @param string $condition 条件
	 * @param string $order     排序方式
	 * @param string $cache     缓存
	 * @return array 获取列表
	 */
	function getList($condition = 'status=3', $order = 'edittime DESC', $cache = '') {
		global $MOD, $items;
		$num   = $this->_db->count($this->_table, $condition, $cache);
		$items = $num;
		$this->_pn->recordsPerPage($this->_pagesize);
		$this->_pn->records($num);
		$sql = "SELECT * FROM {$this->_table}";
		$sql .= $condition ? " WHERE {$condition}" : '';
		$sql .= $order ? " ORDER BY {$order}" : '';
		$sql .= " LIMIT " . ($this->_pn->getPage() - 1) * $this->_pagesize . ',' . $this->_pagesize;
		$lists  = $catids = $CATS = array();
		$result = $this->_db->query($sql, $cache);
		while ($r = $this->_db->fetchArray($result)) {
			$r['alt']   = $r['title'];
			$r['title'] = set_style($r['title'], $r['style']);
			if (strpos($r['linkurl'], '://') === false) {
				$r['linkurl'] = $MOD['linkurl'] . $r['linkurl'];
			}
			$catids[$r['catid']] = $r['catid'];
			$lists[]             = $r;
		}
		if ($catids) {
			$result = $this->_db->query("SELECT catid,catname,linkurl FROM {$this->_db->pre}category WHERE catid IN (" . implode(',', $catids) . ")");
			while ($r = $this->_db->fetchArray($result)) {
				$CATS[$r['catid']] = $r;
			}
			if ($CATS) {
				foreach ($lists as $k => $v) {
					$lists[$k]['catname'] = $v['catid'] ? $CATS[$v['catid']]['catname'] : '';
					$lists[$k]['caturl']  = $v['catid'] ? $MOD['linkurl'] . '?catid=' . $v['catid'] : '';
				}
			}
		}
		return $lists;
	}

	/**
	 * @param $post
	 * @return mixed 添加
	 */
	function add($post) {
		global $MOD, $_userid;
		$post = $this->set($post);

		$this->_db->query(Sql::insert($this->_table, $post, $this->_fields));
		$this->_itemid = $this->_db->insertId();
		$content_table = content_table($this->_moduleid, $this->_itemid, $this->_split, $this->_tableData);
		$this->_db->query("INSERT INTO {$content_table} (itemid,content) VALUES ('$this->_itemid', '$post[content]')");
		$this->update($this->_itemid, $post, $post['content']);
		if ($post['status'] == 3 && $post['username'] && $MOD['credit_add']) {
			credit_add($post['username'], $MOD['credit_add']);
			credit_record($post['username'], $MOD['credit_add'], 'system', lang('my->credit_record_add', array($MOD['name'])), 'ID:' . $this->_itemid);
		}
		$new_urls = array(
			$post['thumb'], $post['thumb1'], $post['thumb2']
		);
		ThumbUpload::clearPicture($this->_moduleid . '_thumb', $new_urls, array(), $_userid);
		EditorUpload::clearDiff($post['content'], '', $_userid);
		return $this->_itemid;
	}

	function edit($post) {
		global $r, $_userid;
		$this->delete($this->_itemid, false);
		$post = $this->set($post);
		$this->_db->query(Sql::update($this->_table, $post, "itemid={$this->_itemid}", '', $this->_fields));
		$content_table = content_table($this->_moduleid, $this->_itemid, $this->_split, $this->_tableData);
		$this->_db->query(Sql::update($content_table, "content='$post[content]'", "itemid=$this->_itemid"));
		$this->update($this->_itemid, $post, $post['content']);
		$old_urls = array(
			$r['thumb1'], $r['thumb2'],$r['thumb3']
		);
		$new_urls = array(
			$post['thumb'], $post['thumb2'], $post['thumb3']
		);
		ThumbUpload::clearPicture($this->_moduleid.'_thumb', $new_urls, $old_urls, $_userid);
		EditorUpload::clearDiff($post['content'], $r['content'], $_userid);
		return true;
	}


	function update($itemid, $item = array(), $content = '') {
		global $MOD;
		$item or $item = $this->_db->getOne("SELECT * FROM {$this->_table} WHERE itemid=$itemid");
		$keyword        = $item['title'] . ',' . str_replace(' ', ',', $item
			['tag']) . ',' . strip_tags(cat_pos($item['catid'], ','));
		$keyword        = str_replace("//", '', addslashes($keyword));
		$item['itemid'] = $itemid;
		$sql            = "keyword='$keyword'";
		$this->_db->query(Sql::update($this->_table, "$sql", "itemid=$itemid"));
	}

	function recycle($itemid) {
		if (is_array($itemid)) {
			foreach ($itemid as $v) {
				$this->recycle($v);
			}
		} else {
			$this->_db->query(Sql::update($this->_table, "status=0", "itemid=$itemid"));
			$this->delete($itemid, false);
			return true;
		}
	}

	function restore($itemid) {
		global $module, $MOD;
		if (is_array($itemid)) {
			foreach ($itemid as $v) {
				$this->restore($v);
			}
		} else {
			$this->_db->query(Sql::update($this->_table, "status=3", "itemid=$itemid"));
			return true;
		}
	}

	function delete($itemid, $all = true) {
		global $MOD;
		if (is_array($itemid)) {
			foreach ($itemid as $v) {
				$this->delete($v, $all);
			}
		} else {
			$this->_itemid = $itemid;
			$r             = $this->getOne();
			if ($all) {
				$userid = get_user($r['username']);
				if ($r['thumb']) PictureUpload::deletePicture($r['thumb'], $userid);
				if ($r['thumb1']) PictureUpload::deletePicture($r['thumb1'], $userid);
				if ($r['thumb2']) PictureUpload::deletePicture($r['thumb2'], $userid);
				if ($r['content']) EditorUpload::clearDiff('', $r['content'], $userid);
				$this->_db->query(Sql::delete($this->_table, "itemid=$itemid"));
				$content_table = content_table($this->_moduleid, $this->_itemid, $this->_split, $this->_tableData);
				$this->_db->query(Sql::delete($content_table, "itemid=$itemid"));
				if ($r['username'] && $MOD['credit_del']) {
					credit_add($r['username'], -$MOD['credit_del']);
					credit_record($r['username'], -$MOD['credit_del'], 'system', lang('my->credit_record_del', array($MOD['name'])), 'ID:' . $this->_itemid);
				}
			}
		}
	}

	function check($itemid) {
		global $_username, $DT_TIME, $MOD;;
		if (is_array($itemid)) {
			foreach ($itemid as $v) {
				$this->check($v);
			}
		} else {
			$this->_itemid = $itemid;
			$item          = $this->getOne();
			if ($MOD['credit_add'] && $item['username'] && $item['hits'] < 1) {
				credit_add($item['username'], $MOD['credit_add']);
				credit_record($item['username'], $MOD['credit_add'], 'system', lang('my->credit_record_add', array($MOD['name'])), 'ID:' . $this->_itemid);
			}
			$editdate = timetodate($DT_TIME, 3);
			$this->_db->query(Sql::update($this->_table, "status=3,hits=hits+1,editor='$_username',edittime=$DT_TIME,editdate='$editdate'", "itemid=$itemid"));
			return true;
		}
	}

	function reject($itemid) {
		global $_username, $DT_TIME;
		if (is_array($itemid)) {
			foreach ($itemid as $v) {
				$this->reject($v);
			}
		} else {
			$this->_db->query(Sql::update($this->_table, "status=1,editor='$_username'", "itemid=$itemid"));
			return true;
		}
	}

	function expire($condition = '') {
		global $DT_TIME;
		$this->_db->query(Sql::update($this->_table, "status=4", "status=3 AND totime>0 AND totime<$DT_TIME $condition"));
	}

	function clear($condition = 'status=0') {
		$result = $this->_db->query("SELECT itemid FROM {$this->_table} WHERE $condition ");
		while ($r = $this->_db->fetchArray($result)) {
			$this->delete($r['itemid']);
		}
	}

	function level($itemid, $level) {
		$itemids = is_array($itemid) ? implode(',', $itemid) : $itemid;
		$this->_db->query(Sql::update($this->_table, "level=$level", "itemid IN ($itemids)"));
	}

	function type($itemid, $typeid) {
		$itemids = is_array($itemid) ? implode(',', $itemid) : $itemid;
		$this->_db->query(Sql::update($this->_table, "typeid=$typeid", "itemid IN ($itemids)"));
	}

	function refresh($itemid) {
		global $DT_TIME;
		$editdate = timetodate($DT_TIME, 3);
		$itemids  = is_array($itemid) ? implode(',', $itemid) : $itemid;
		$this->_db->query(Sql::update($this->_table, "edittime='$DT_TIME',editdate='$editdate'", "itemid IN ($itemids)"));
	}

	function _update($username) {
		global $DT_TIME;
		$this->_db->query(Sql::update($this->_table, "status=4", "status=3 AND totime>0 AND totime<$DT_TIME AND username='$username'"));
	}

}